package Network.Echo;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

/**
 * Udp回显服务器客户端实现
 */
public class UdpEchoClient {
    private DatagramSocket socket = null;
    private int ServerPort;
    private String ServerIP;
    //传入服务器IP和端口号
    public UdpEchoClient(String ip,int port) throws SocketException {
        this.ServerIP = ip;
        this.ServerPort = port;
        socket = new DatagramSocket();
    }
    public void start() throws IOException {
        System.out.println("客户端启动");
        Scanner scan = new Scanner(System.in);
        while(true){
            System.out.print("->");
            //1.发送请求给服务器
            while(!scan.hasNext()){
                break;
            }
            String req = scan.next();
            DatagramPacket reqData = new DatagramPacket(req.getBytes(),req.getBytes().length,
                    InetAddress.getByName(ServerIP),ServerPort);
            socket.send(reqData);
            //2.接收服务器返回的响应
            DatagramPacket respData = new DatagramPacket(new byte[4096],4096);
            socket.receive(respData);
            String resp = new String(respData.getData(),0,respData.getLength());
            //将结果打印
            System.out.println(resp);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient udpEchoClient = new UdpEchoClient("127.0.0.1", 9090);
        udpEchoClient.start();
    }
}
